package com.ruoyi.exam.service.impl;

import java.beans.Transient;
import java.io.File;
import java.io.IOException;
import java.util.*;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.exam.dto.QuestionsDto;
import com.ruoyi.exam.utils.OfficeToPdf;
import com.ruoyi.exam.utils.WordUtil;
import com.spire.doc.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.exam.mapper.QuestionsMapper;
import com.ruoyi.exam.domain.Questions;
import com.ruoyi.exam.service.IQuestionsService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 试题管理Service业务层处理
 *
 * @author ruoyi
 * @date 2021-10-12
 */
@Service
public class QuestionsServiceImpl implements IQuestionsService
{
    @Autowired
    private QuestionsMapper questionsMapper;

    /**
     * 查询试题管理
     *
     * @param id 试题管理主键
     * @return 试题管理
     */
    @Override
    public Questions selectQuestionsById(String id)
    {
        return questionsMapper.selectQuestionsById(id);
    }

    /**
     * 查询试题管理列表
     *
     * @param questions 试题管理
     * @return 试题管理
     */
    @Override
    public List<Questions> selectQuestionsList(Questions questions)
    {
        return questionsMapper.selectQuestionsList(questions);
    }

    /**
     * 新增试题管理
     *
     * @param questions 试题管理
     * @return 结果
     */
    @Override
    public int insertQuestions(Questions questions)
    {
        questions.setId(UUID.randomUUID().toString().replaceAll("-",""));
        questions.setCreateTime(DateUtils.getNowDate());
        return questionsMapper.insertQuestions(questions);
    }

    /**
     * 批量新增试题
     *
     * @param questionsDto 试题
     * @return 结果
     */
    @Override
    @Transient
    public int insertQuestionsAll(QuestionsDto questionsDto) {
        Questions questions = new Questions();
        for (int i = 0; i < questionsDto.getQuestionsList().size(); i++) {
            Map<String, String> questionItem = questionsDto.getQuestionsList().get(i);
            questions.setId(UUID.randomUUID().toString().replaceAll("-",""));
            questions.setChapter(questionsDto.getChapter());
            questions.setFestival(questionsDto.getFestival());
            questions.setContent(questionItem.get("content"));
            questions.setDel(questionsDto.getDel());
            questions.setQuestionType(questionsDto.getQuestionType());
            questions.setEduName(questionsDto.getEduName());
            questions.setFilePath(questionItem.get("filePath"));
            questions.setLevelName(questionsDto.getLevelName());
            questions.setCreateTime(DateUtils.getNowDate());
            questions.setUserId(questionsDto.getUserId());
            questionsMapper.insertQuestions(questions);
        }
        return 1;
    }

    /**
     * 修改试题管理
     *
     * @param questions 试题管理
     * @return 结果
     */
    @Override
    public int updateQuestions(Questions questions)
    {
        questions.setUpdateTime(DateUtils.getNowDate());
        return questionsMapper.updateQuestions(questions);
    }

    /**
     * 批量删除试题管理
     *
     * @param ids 需要删除的试题管理主键
     * @return 结果
     */
    @Override
    public int deleteQuestionsByIds(String[] ids)
    {
        return questionsMapper.deleteQuestionsByIds(ids);
    }

    /**
     * 删除试题管理信息
     *
     * @param id 试题管理主键
     * @return 结果
     */
    @Override
    public int deleteQuestionsById(String id)
    {
        return questionsMapper.deleteQuestionsById(id);
    }

    @Override
    public AjaxResult questionsSplitContent(MultipartFile file) {
        try
        {
            // 上传试卷文件路径
            String filePath = RuoYiConfig.getUploadQuestionPath();
//             上传的文件路径
            String fileProfilePath = RuoYiConfig.getProfile();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            // 获取文件后缀
            String extension = FileUploadUtils.getExtension(file);
            // 去除文件地址字符串的前缀
            fileName = fileName.replace(Constants.RESOURCE_PREFIX+"/","");
            // 处理word文件，并将内容格式化出来
            List<Map<String, String>> result = wordSplit(fileProfilePath +"/"+ fileName, extension);
            OfficeToPdf.deleteFile(new File(fileProfilePath +"/"+ fileName));
            AjaxResult ajax = AjaxResult.success();
            ajax.put("rows", result);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 根据传入的路径拆分word，变成多个word
     * @param wordPath
     */
    public List<Map<String,String>> wordSplit(String wordPath,String extension) throws IOException {
        List<Map<String, String>> result = new ArrayList<>();
        // 上传试卷文件路径
        String filePath = RuoYiConfig.getUploadQuestionPath();
        //创建Document对象
        Document document = new Document();
        //加载要拆分的文档
        document.loadFromFile(wordPath);
        System.out.println(document.getSections());
        //声明新的Document对象
        Document newWord;
        //遍历源文档中的节
        for (int i = 0; i < document.getSections().getCount(); i++) {
            //初始化新的Document对象
            newWord = new Document();
            //将源文档中的指定节复制到新文档
            newWord.getSections().add(document.getSections().get(i).deepClone());
            String descFileName = File.separator+UUID.randomUUID().toString().replaceAll("-","")+"."+extension;
            newWord.saveToFile(filePath+descFileName);
            Map<String,String> resMap = new HashMap<String,String>();
            String wordString = WordUtil.ReadDoc(filePath+descFileName);
            resMap.put("content",wordString);
            resMap.put("filePath",descFileName);
            result.add(resMap);
        }

        return result;

    }
}
